<?php

namespace app\api\model;

use app\common\model\BaseModel;

class Address extends BaseModel
{
    protected $autoWriteTimestamp = 'int';
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function province()
    {
        return $this->hasOne(Area::class, 'id', 'province_id');
    }
    public function city()
    {
        return $this->hasOne(Area::class, 'id', 'city_id');
    }
    public function area()
    {
        return $this->hasOne(Area::class, 'id', 'area_id');
    }
    /**
     * 添加用户地址
     */
    public function add(array $data)
    {
        return $this->allowField(true)->save($data);
    }

    /**
     * 用户地址
     */
    public static function getByUserId($userId)
    {
        return self::with(['province', 'city', 'area'])->where('user_id', $userId)->order('createtime desc')->select();
    }

    /**
     * 更新地址
     */
    public static function updateNotDefault($userId)
    {
        return self::where('user_id', $userId)->update(['is_default' => 0]);
    }

    /**
     * 获取用户默认地址
     */
    public static function getDefaultAddress($userId)
    {
        $address = self::with(['province', 'city', 'area'])->where('is_default', '>', 1)->where('user_id', $userId)->find();
        if (!$address) {
            $addresses = self::getByUserId($userId);
            if ($addresses) {
                $address = $addresses[0];
            }
        }
        return $address;
    }
}
